package com.example.thegreatwall.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.thegreatwall.common.R;
import com.example.thegreatwall.dto.WxLoginRequest;
import com.example.thegreatwall.dto.WxLoginResponse;
import com.example.thegreatwall.entity.Users;
import com.example.thegreatwall.service.UsersService;
import com.example.thegreatwall.utils.*;
import com.google.gson.JsonObject;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RequestMapping("/user")
@CrossOrigin(origins = "*") //无论什么源都可以访问  不写这个不允许跨域
@RestController
public class UsersController{
    @Autowired
    private UsersService usersService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 根据id查询用户信息
     * @param id 用户id
     * @return
     */
    @GetMapping("/getUserById")
    public R getUserById(@Param("id") Integer id){
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        Users user = usersService.getOne(queryWrapper);
        return new R().addDate("userInfo",user);
    }

    /**
     * 修改用户信息
     * @param user 用户对象
     * @return
     */
    @PostMapping("/updUserById")
    public R updUserById(@RequestBody Users user){
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getUserId());
        boolean update = usersService.update(user, queryWrapper);
        if (update){
            return new R().addDate("msg","修改成功！");
        }else {
            return new R().addDate("msg","修改失败！");
        }
    }


    @PostMapping("/login")
    public ResponseEntity<BaseResponse<WxLoginResponse>> login(@RequestBody WxLoginRequest request) throws Exception {
        JSONObject sessionInfo = WxUtil.getSessionInfo(request.getCode());
        String openid = sessionInfo.getString("openid");

        if (openid == null) throw new RuntimeException("登录失败");

        // 查询或注册用户 微信授权登录
            Users user = usersService.findOrCreateUser(openid);

        // 生成 JWT
        String token = JwtUtil.generateToken(openid);

        // 存入 Redis：30分钟有效期
//        redisTemplate.opsForValue().set(ProFixRedis.TOKEN + token, openid, 30, TimeUnit.MINUTES);
        WxLoginResponse response = new WxLoginResponse(token, openid,user.getStatus());
        return ResponseEntity.ok(BaseResponse.success(response));
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public ResponseEntity<String> logout(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");

        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
//            redisTemplate.delete(ProFixRedis.TOKEN + token);
            return ResponseEntity.ok("退出登录成功");
        }

        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("无效的请求");
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/userInfo")
    public ResponseEntity<?> getUserInfo(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");

        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Token 缺失");
        }

        String token = authHeader.substring(7);

//        // 检查 Redis 是否存在该 token
//        String openidFromRedis = redisTemplate.opsForValue().get(ProFixRedis.TOKEN + token);
//        if (openidFromRedis == null) {
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("登录已失效，请重新登录");
//        }

        // 验证 JWT 合法性
        if (!JwtUtil.isTokenValid(token)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("无效的 Token");
        }

        // 获取 openid（可从 token 中解析，也可用 Redis 值）
        String openid = JwtUtil.getOpenidFromToken(token);
        System.out.println(openid);
        if (openid == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("无法获取 openid");
        }
        // 查询用户信息
        Users user = usersService.findOrCreateUser(openid);
        System.out.println("用户实体完整信息：" + user);  // 打印整个对象
        return ResponseEntity.ok(BaseResponse.success(user));
    }

    @GetMapping(value = "/checkstatus")
    public int checkStatus(@Param("user_id")int user_id) {
        return this.usersService.checkstatus(user_id);
    }

}